<script setup lang="ts">
import { ref, defineProps, defineEmits, onMounted } from 'vue'

interface Threshold {
  min: number
  max: number
}

const props = defineProps<{
  thresholds: { [key: string]: Threshold }
}>()

const emit = defineEmits<{
  (e: 'updateThresholds', thresholds: { [key: string]: Threshold }): void
}>()

const localThresholds = ref({ ...props.thresholds })

const fetchThresholds = async () => {
  try {
    const response = await fetch('/api/threshold')
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    const data = await response.json()
    data.thresholds.forEach((threshold: any) => {
      const type = threshold.parameterType === 0 ? 'humidity' : threshold.parameterType === 1 ? 'temperature' : 'light'
      localThresholds.value[type] = { min: parseInt(threshold.minValue), max: parseInt(threshold.maxValue) }
    })
  } catch (error) {
    console.error('获取阈值失败:', error)
  }
}

const updateThreshold = async (type: string, field: 'min' | 'max', value: number) => {
  localThresholds.value[type][field] = value
  try {
    const response = await fetch('/api/threshold/modify', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: type === 'temperature' ? 1 : type === 'humidity' ? 0 : 2,
        min: localThresholds.value[type].min.toString(),
        max: localThresholds.value[type].max.toString()
      })
    })
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    const updatedThresholds = await response.json()
    updatedThresholds.thresholds.forEach((threshold: any) => {
      const type = threshold.parameterType === 0 ? 'humidity' : threshold.parameterType === 1 ? 'temperature' : 'light'
      localThresholds.value[type] = { min: parseInt(threshold.minValue), max: parseInt(threshold.maxValue) }
    })
    emit('updateThresholds', localThresholds.value)

    // 将最新的阈值存储到 localStorage
    localStorage.setItem('thresholds', JSON.stringify(localThresholds.value))
  } catch (error) {
    console.error('修改阈值失败:', error)
  }
}

onMounted(() => {
  fetchThresholds()
})
</script>

<template>
  <div class="card shadow">
    <div class="card-header">
      <h5 class="mb-0"><i class="bi bi-gear"></i> 阈值设置</h5>
    </div>
    <div class="card-body">
      <div v-for="(threshold, type) in localThresholds" :key="type" class="mb-3">
        <h6>{{ type.charAt(0).toUpperCase() + type.slice(1) }}</h6>
        <div class="input-group mb-2">
          <span class="input-group-text">最小值</span>
          <input 
            type="number" 
            class="form-control" 
            :value="threshold.min" 
            @input="updateThreshold(type, 'min', parseInt($event.target.value))"
          />
        </div>
        <div class="input-group">
          <span class="input-group-text">最大值</span>
          <input 
            type="number" 
            class="form-control" 
            :value="threshold.max" 
            @input="updateThreshold(type, 'max', parseInt($event.target.value))"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.card {
  margin-block-start: 20px;
}
</style>